<template>
  <div class="project-application">
    <h2 class="form-title">创业项目申请</h2>
    <form @submit.prevent="submitApplication" class="application-form">
      <div class="form-group">
        <label for="projectName">项目名称</label>
        <input type="text" id="projectName" v-model="formData.projectName"
               placeholder="请输入项目名称" required>
      </div>
      <div class="form-group">
        <label>项目类型</label>
        <div class="type-select">
          <select v-model="formData.projectType" required>
            <option value="" disabled selected>请选择项目类型</option>
            <option v-for="type in projectTypes" :key="type.id" :value="type.type">
              {{ type.type }}
            </option>
          </select>
          <div class="select-arrow"></div>
        </div>
      </div>
      <div class="form-group">
        <label>指导老师</label>
        <div class="type-select">
          <select v-model="formData.supervisor" required>
            <option value="" disabled selected>请选择指导老师</option>
            <option v-for="supervisor in supervisorOptions"
                    :key="supervisor.id"
                    :value="supervisor.name">
              {{ supervisor.name }}
            </option>
          </select>
          <div class="select-arrow"></div>
        </div>
      </div>
      <div class="form-group">
        <label>评审专家</label>
        <div class="type-select">
          <select v-model="formData.reviewer" required>
            <option value="" disabled selected>请选择评审专家</option>
            <option v-for="reviewer in reviewerOptions"
                    :key="reviewer.id"
                    :value="reviewer.name">
              {{ reviewer.name }}
            </option>
          </select>
          <div class="select-arrow"></div>
        </div>
      </div>
      <div class="form-group">
        <label for="projectOverview">项目概述</label>
        <textarea id="projectOverview" v-model="formData.projectOverview"
                  placeholder="简要描述你的项目（200字以内）" required></textarea>
      </div>
      <div class="form-group">
        <div class="git-label">
          <label for="gitRepo">Gitee仓库地址</label>
          <a href="https://gitee.com/" target="_blank" class="git-link">
            <i class="el-icon-link"></i>
            前往Gitee网站
          </a>
        </div>
        <input type="url" id="gitRepo" v-model="formData.gitRepo"
               placeholder="请输入Gitee代码仓库地址" required>
      </div>
      <!-- 新增队友选择栏 -->
      <el-cascader
          v-model="formData.teammates"
          :props="cascaderPropss"
          collapse-tags
          clearable
          filterable
          placeholder="申请人自动成为队长（请选择你的团队成员（勾选））"
          style="width: 100%"
          :show-all-levels="false"
          multiple
      ></el-cascader>
      <div class="form-group">
        <label for="teamIntroduction">团队介绍</label>
        <textarea id="teamIntroduction" v-model="formData.teamIntroduction"
                  placeholder="介绍你的团队构成和成员背景" required></textarea>
      </div>

      <!-- 联系邮箱 -->
      <div class="form-group">
        <label for="contactEmail">联系邮箱</label>
        <input type="email" id="contactEmail" v-model="formData.contactEmail"
               placeholder="请输入联系邮箱" required>
      </div>
      <div class="form-group">
        <label>商业计划书</label>
        <el-upload
            class="file-upload"
            action="http://47.97.65.149:9090/project/upload"
            :headers="{ token: user.token }"
            :file-list="fileList"
            :on-success="handleFileSuccess"
            :on-error="handleFileError"
            :on-progress="handleFileProgress"
            :before-upload="beforeFileUpload"
            :limit="1"
            :on-exceed="handleExceed"
            :show-file-list="false"
            
        >
        <el-button type="primary">
          <i class="el-icon-upload"></i>
          {{ fileUrl ? '已上传文件' : '点击上传文件' }}
        </el-button>
        <div v-if="isUploading" class="upload-progress">
          上传进度: {{ uploadProgress }}%
          <el-button type="text" @click.stop="cancelUpload">取消</el-button>
        </div>
        </el-upload>
        <div v-if="fileUrl" class="file-preview">
          <i class="el-icon-document"></i>
          {{ fileName }}
          <el-button type="text" @click="removeFile">移除</el-button>
        </div>
      </div>

      <button type="submit" class="submit-btn" :disabled="isSubmitting || !fileUrl">
        <span v-if="!isSubmitting">提交申请</span>
        <span v-else class="loading"></span>
      </button>
    </form>

    <div v-if="message" :class="['message', messageType]">
      <i :class="messageIcon"></i>
      {{ message }}
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 新增数据项
      cascaderPropss: {
        lazy: true,
        multiple: true,
        emitPath: false, // 只返回节点自身值
        value: 'id',
        label: 'name',
        leaf: 'isLeaf',
        lazyLoad: this.loadTeamOptions
      },
      cascaderProps: {
        multiple: true,
        checkStrictly: true,
        emitPath: false
      },
      user: JSON.parse(localStorage.getItem('honey-user') || '{}'),
      fileList: [],
      fileName: '',
      cancelToken: null,
      formData: {
        projectType: '',
        supervisor: '',
        projectName: '',
        businessPlan: '',
        teammates: [],
        projectOverview: '',
        teamIntroduction: '',
        contactEmail: '',
        reviewer: '',
        gitRepo: ''
      },
      reviewerOptions: [

      ],
      projectTypes: [],
      supervisorOptions: [],
      isSubmitting: false,
      message: '',
      messageType: 'success',
      isUploading: false,
      uploadProgress: 0,
      uploadError: null,
      uploadController: null,
      fileUrl: null
    };
  },
  computed: {
    messageIcon() {
      return this.messageType === 'success' ? 'icon-success' : 'icon-error';
    }
  },
  created() {
    this.selectType(),
        this.load()

  },
  methods: {

    // 文件上传前验证
    beforeFileUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10; // 限制文件大小为 10MB

      if (!isLt10M) {
        this.$message.error('文件大小不能超过 10MB!');
        return false;
      }

      this.isUploading = true;
      this.uploadProgress = 0;
      this.fileName = file.name;
      return true;
    },

    selectType(){

        this.$request.get('/project/selectProjectType')
            .then(res=>{
              this.projectTypes=res.data
            })
      this.$request.get('/project/selectSupervisor')
          .then(res=>{
            this.supervisorOptions=res.data
          })

    },
    load(){
      this.$request.get('/project/selectReviewerOptions')
          .then(res=>{
            this.reviewerOptions=res.data
          })
    },
    loadTeamOptions(node, resolve) {
      const { level, label: className } = node; // 使用 className 作为查询条件

      // 加载班级（第一级）
      if (level === 0) {
        this.$request.get('/project/selectClasses')
            .then(({ data }) => {
              // 确保接口返回数据格式正确
              const nodes = data.map(cls => ({
                id: cls.id,
                name: cls.classname,  // 使用 classname 作为 name
                isLeaf: false,       // 班级节点不是叶子节点，可以继续加载学生
                hasChildren: true    // 明确标识有子节点
              }));
              resolve(nodes);
            })
            .catch(error => {
              console.error('班级加载失败:', error);
              resolve([]); // 失败时返回空数组防止卡死
            });
      }

// 加载学生（第二级）
      else if (level === 1) {
        // 添加防抖判断
        if (!className) {
          resolve([]);
          return;
        }

        // 根据班级名称查询学生
        this.$request.get(`/project/selectStudents?className=${encodeURIComponent(className)}`)
            .then(({ data }) => {
              const nodes = data.map(stu => ({
                id: stu.id,
                name: stu.name, // 注意字段名匹配
                isLeaf: true            // 学生节点是叶子节点，不再继续加载
              }));
              resolve(nodes);
            })
            .catch(error => {
              console.error('学生加载失败:', error);
              resolve([]);
            });
      }},
    // 文件上传进度处理
    handleFileProgress(event, file, fileList) {
      this.uploadProgress = Math.round((event.loaded / event.total) * 100)
    },

    // 文件上传成功处理
    handleFileSuccess(response, file) {
      this.isUploading = false;
      if (response.code === '200') {
        this.fileUrl = response.data;
        this.fileName = file.name; // 显示上传的文件名
        this.$message.success('文件上传成功');
      } else {
        this.$message.error(response.msg);
      }
    },
    // 文件上传失败处理
    handleFileError(err) {
      this.isUploading = false
      this.$message.error('文件上传失败')
    },

    // 取消上传
    cancelUpload() {
      this.isUploading = false
      this.uploadProgress = 0
      this.cancelToken && this.cancelToken.cancel('用户取消上传')
    },

    // 移除文件
    removeFile() {
      this.fileUrl = '';
      this.fileName = '';
      this.fileList = [];
    },

    // 文件超出限制
    handleExceed() {
      this.$message.warning('每次只能上传一个文件')
    },
    async submitApplication() {
      if (!this.formData.projectName ||
          !this.formData.projectType ||
          !this.formData.supervisor ||
          !this.formData.reviewer ||
          !this.formData.projectOverview ||
          !this.formData.gitRepo ||
          !this.formData.teammates ||
          !this.formData.teamIntroduction ||
          !this.formData.contactEmail ||
          !this.fileUrl) {
        this.showMessage('请填写所有必填信息', 'error');
        return;
      }
      if (!this.fileUrl) {
        this.showMessage('请先上传商业计划书', 'error');
        return;
      }

      this.isSubmitting = true;
      try {
        const response = await this.$request.post('/project/application', {
          ...this.formData,
          businessPlan: this.fileUrl
        }).then(res => {
          if (res.code === '200') {
            this.user.verificationCode = ''
            this.$message.success('提交成功')
            this.resetForm();
          } else {
            this.$message.error(res.msg)
          }})






      } catch {

      } finally {
        this.isSubmitting = false;
      }
    },

    handleSubmitError(error) {
      const errorMap = {
        400: '请求参数错误',
        413: '文件大小超出限制',
        500: '服务器错误，请稍后重试'
      };
      const message = error.response
          ? errorMap[error.response.status] || error.response.data.message
          : '网络连接异常';
      this.showMessage(`提交失败：${message}`, 'error');
    },

    resetForm() {
      this.formData = {
        projectType: '',
        supervisor: '',
        projectName: '',
        businessPlan: '',
        projectOverview: '',
        teamIntroduction: '',
        contactEmail: '',
        reviewer: '',
        gitRepo: '',
        teammates: []
      };
      this.fileUrl = null;
      this.resetFileInput();
    },

    showMessage(message, type) {
      this.message = message;
      this.messageType = type;
      setTimeout(() => {
        this.message = '';
      }, 3000);
    }
  }
};
</script>

<style scoped>
.expert-select {
  width: 100%;
}

.el-select__tags {
  flex-wrap: nowrap;
  overflow-x: auto;
  max-width: 100%;
}

.el-select .el-tag {
  margin: 2px;
  flex-shrink: 0;
}
/* 新增级联选择器样式 */
.el-cascader__tags {
  flex-wrap: wrap;
  row-gap: 5px;
}
.el-cascader__tags .el-tag {
  margin: 2px;
  background-color: #f0f4ff;
  border-color: #c7d4fe;
}
.el-cascader__tags .el-tag__close {
  color: #3b82f6;
}
.el-cascader__tags .el-tag__close:hover {
  background-color: #bfdbfe;
}
.el-select-dropdown__item {
  padding: 8px 20px;
}
/* 新增样式 */
.upload-status {
  display: flex;
  align-items: center;
  gap: 8px;
}

.upload-cancel {
  color: #ef4444;
  cursor: pointer;
  font-size: 0.9em;
}

.upload-cancel:hover {
  text-decoration: underline;
}

.file-actions {
  margin-top: 8px;
  display: flex;
  gap: 12px;
  align-items: center;
}

.file-link {
  color: #3b82f6;
  text-decoration: none;
}

.file-link:hover {
  text-decoration: underline;
}

.reupload-btn {
  background: none;
  border: 1px solid #e2e8f0;
  padding: 4px 12px;
  border-radius: 4px;
  cursor: pointer;
}

.reupload-btn:hover {
  background: #f8fafc;
}

.upload-error {
  color: #dc2626;
  font-size: 0.9em;
  margin-top: 4px;
}

button:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}
.type-select {
  position: relative;
}
select {
  appearance: none;
  width: 100%;
  padding: 0.8rem 1.2rem;
  border: 2px solid #e2e8f0;
  border-radius: 8px;
  font-size: 1rem;
  background: white;
  cursor: pointer;
  transition: all 0.3s ease;
}

select:focus {
  border-color: #4f46e5;
  box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
  outline: none;
}

.select-arrow {
  position: absolute;
  top: 50%;
  right: 1rem;
  transform: translateY(-50%);
  width: 12px;
  height: 12px;
  background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%234b5563"><path d="M7 10l5 5 5-5z"/></svg>');
  pointer-events: none;
}
.project-application {
  max-width: 800px;
  margin: 2rem auto;
  padding: 2.5rem;
  background: #ffffff;
  border-radius: 16px;
  box-shadow: 0 8px 30px rgba(0,0,0,0.1);
}

.form-title {
  text-align: center;
  color: #2c3e50;
  font-size: 2rem;
  margin-bottom: 2rem;
  font-weight: 600;
}

.application-form {
  display: grid;
  gap: 1.5rem;
}

.form-group {
  position: relative;
}

label {
  display: block;
  margin-bottom: 0.8rem;
  color: #4a5568;
  font-weight: 500;
  font-size: 0.95rem;
}

input, textarea {
  width: 100%;
  padding: 0.8rem 1.2rem;
  border: 2px solid #e2e8f0;
  border-radius: 8px;
  font-size: 1rem;
  transition: all 0.3s ease;
}

input:focus, textarea:focus {
  border-color: #4f46e5;
  box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
  outline: none;
}

textarea {
  min-height: 120px;
  resize: vertical;
}

.file-upload {
  position: relative;
}

.upload-btn {
  display: flex;
  align-items: center;
  padding: 0.8rem 1.2rem;
  background: #f8fafc;
  border: 2px dashed #cbd5e1;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.upload-btn:hover {
  border-color: #4f46e5;
  background: rgba(79, 70, 229, 0.05);
}

.upload-icon {
  width: 20px;
  height: 20px;
  margin-right: 0.8rem;
  background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%234f46e5"><path d="M19 13v5a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-5h2v5h12v-5h2zm-7-1.414l3.293-3.293 1.414 1.414L12 15.414l-4.707-4.707 1.414-1.414L11 11.586V2h2v9.586z"/></svg>');
}

input[type="file"] {
  opacity: 0;
  position: absolute;
  width: 1px;
  height: 1px;
}

.submit-btn {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  padding: 1rem;
  background: linear-gradient(135deg, #4f46e5, #6d63ff);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(79, 70, 229, 0.3);
}

.loading {
  width: 24px;
  height: 24px;
  border: 3px solid #fff;
  border-radius: 50%;
  border-top-color: transparent;
  animation: spin 0.8s linear infinite;
}

.message {
  display: flex;
  align-items: center;
  padding: 1rem;
  margin-top: 1.5rem;
  border-radius: 8px;
  font-weight: 500;
}

.message.success {
  background: #f0fdf4;
  color: #16a34a;
}

.message.error {
  background: #fef2f2;
  color: #dc2626;
}

.icon-success::before,
.icon-error::before {
  content: '';
  display: inline-block;
  width: 20px;
  height: 20px;
  margin-right: 0.8rem;
}

.icon-success::before {
  background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%2316a34a"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/></svg>');
}

.icon-error::before {
  background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%23dc2626"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z"/></svg>');
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

@media (max-width: 768px) {
  .project-application {
    margin: 1rem;
    padding: 1.5rem;
  }
}
@media (max-width: 480px) {
  select {
    font-size: 0.9rem;
    padding: 0.7rem 1rem;
  }
}
</style>